package behavioral.observer;

import java.util.ArrayList;
import java.util.List;

/**
 * 观察者模式
 * 一个对象（目标对象）的状态发生改变，所有的依赖对象（观察者对象）都将得到通知，进行广播通知。
 */
class Subject{
    private List<Observer> observerList = new ArrayList<>();

    public void add(Observer observer){
        observerList.add(observer);
    }

    public void notifyAllObserver(Integer state){
        for (Observer observer : observerList) {
            observer.updateState(state);
        }
    }

    public void showAllObserver(){
        for (Observer observer : observerList) {
            System.out.println(observer.getName()+":"+observer.getState());
        }
    }
}


abstract class Observer{
    protected static Subject subject = new Subject();
    protected Integer state;
    protected String name;

    public void setState(Integer state) {
        this.state = state;
        System.out.println("通知所有观察者");
        Observer.subject.notifyAllObserver(state);
    }
    public abstract void updateState(Integer state);

    public Integer getState(){
        return this.state;
    }
    public String getName(){
        return this.name;
    }

    public void showAll(){
        Observer.subject.showAllObserver();
    }
}


class AObserver extends Observer{

    public AObserver(Integer state,String name) {
        this.state = state;
        this.name = name;
        Observer.subject.add(this);
    }

    @Override
    public void updateState(Integer state){
        //特殊处理
        System.out.println(this.name+":更新状态吗");
        this.state = state;
    }
}


class BObserver extends Observer{

    public BObserver(Integer state,String name) {
        this.state = state;
        this.name = name;
        Observer.subject.add(this);
    }

    @Override
    public void updateState(Integer state){
        //特殊处理
        System.out.println(this.name+":更新状态吗");
        this.state = state;
    }
}

class Test{
    public static void main(String[] args) {
        Observer observer = new AObserver(15,"A");
        Observer observer1 = new BObserver(20,"B");
        observer.showAll();
        observer.setState(30);
        observer.showAll();
    }
}
